package com.ssish.saas.eccs.controller;

import com.alibaba.fastjson.JSONObject;
import com.ssish.saas.eccs.dto.BenefitDto;
import com.ssish.saas.eccs.dto.BenefitInfoDto;
import com.ssish.saas.eccs.dto.BenefitPrintDto;
import com.ssish.saas.eccs.dto.CoverageDto;
import com.ssish.saas.eccs.dto.IdCardDto;
import com.ssish.saas.eccs.model.*;
import com.ssish.saas.eccs.service.*;
import com.ssish.saas.eccs.util.DateUtils;
import com.ssish.saas.eccs.util.EncryptUtil;
import com.ssish.saas.eccs.util.JsonResult;
import com.ssish.saas.eccs.util.PrinttemplateConfig;
import com.ssish.saas.eccs.util.XmlUtil;
import com.ssish.saas.eccs.vo.BenefitDetailInfoVo;
import com.ssish.saas.eccs.vo.BenefitShowVo;
import com.ssish.saas.eccs.vo.PolicyVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("eccs福利查询接口文档")
@RefreshScope
@RestController
@RequestMapping("/benefit")
public class BenefitController  extends  BaseController{
    @Value("${eccs.user.key}")
    private String userKey;
    
    @Value("${eccs.print.url}")
   	private String printUrl;
    
    @Value("${eccs.url}")
   	private String url;
    
    @Autowired
    private BenefitSerivice benefitSerivice;
    @Autowired
    private PayorService payorService;
    @Autowired
    private PlanMastService planMastService;

    @Autowired
    private LoginService loginService;
    @ApiOperation("福利查询会员列表")
    @PostMapping("/getMemberInfo")
    public JsonResult<List<BenefitShowVo>> getMemberInfo(@RequestBody BenefitDto benefitDto){
        if(StringUtils.isBlank(benefitDto.getCardNo()) && StringUtils.isBlank(benefitDto.getEmployeeName())
          &&StringUtils.isBlank(benefitDto.getIdNumber())&& StringUtils.isBlank(benefitDto.getPolicyNo())){
            return JsonResult.err("请输入查询关键字",JsonResult.PARAM_ERROR);
        }
        try {
            List<BenefitShowVo> benefitShowVos =  benefitSerivice.getMemberInfo(benefitDto);
            if(benefitShowVos.size() == 0){
                return JsonResult.err("未找到有效保单！",JsonResult.RESULT_ERROR);
            }
            PolicyVo policyVo = new PolicyVo();

            return JsonResult.ok(benefitShowVos);
        } catch (Exception e) {
            log.error("福利查询会员列表接口异常"+e.getMessage());
            return JsonResult.err("福利查询会员列表接口报错！",JsonResult.EXCEPTION);
        }

    }
    @ApiOperation("福利查询详细信息")
    @GetMapping("/benefitDetail/{employPlanId}")
    public JsonResult<BenefitDetailInfoVo> getBenefitDetailInfo(@PathVariable("employPlanId") String employPlanId, HttpServletRequest request){
        try {
            EmpPlanView employeePlan = benefitSerivice.getEmpPlanViewInfoById(Long.valueOf(employPlanId));
            if(employeePlan == null){
                return JsonResult.err("未找到有效保单！",JsonResult.RESULT_ERROR);
            }
            Employee employee = benefitSerivice.getEmployeeInfo(employeePlan.getEmployeeId().trim());
            if(employee == null){
                return JsonResult.err("未找到有效保单！",JsonResult.RESULT_ERROR);
            }
            BenefitDetailInfoVo benefitDetailInfoVo = new BenefitDetailInfoVo();
            PolicyVo policyVo = new PolicyVo();
            getPolicyInfo(policyVo,employee,employeePlan);
            benefitDetailInfoVo.setPolicyVo(policyVo);
            SymUser user=(SymUser)request.getSession().getAttribute(userKey);
            //SymUser user = loginService.isValidUserInfo("EEMFEE",null);
            List<CoverageDto> coverageDtos = benefitSerivice.getCoverageList(Long.valueOf(employPlanId),user,employeePlan,employee);
            benefitDetailInfoVo.setCoverageDtoList(coverageDtos);
            return JsonResult.ok(benefitDetailInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("福利查询详细信息"+e.getMessage());
            return JsonResult.err("福利查询详细信息报错！",JsonResult.EXCEPTION);
        }
    }

    @ApiOperation("获取就诊科室列表")
    @GetMapping("/getCaseInfoList")
    public JsonResult<List<Map<String,Object>>> getBenefitDetailInfo(HttpServletRequest request){
        try {
            SymUser user = (SymUser)request.getSession().getAttribute(userKey);
            //SymUser user = new SymUser();
            //user.setUsrid("EEMFEE");
            List<Map<String,Object>> caseMapList = benefitSerivice.getCaseInfoList(user);
            return JsonResult.ok(caseMapList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取就诊科室列表"+e.getMessage());
            return JsonResult.err("获取就诊科室列表报错！",JsonResult.EXCEPTION);
        }

    }
    private void getPolicyInfo(PolicyVo policyVo,Employee employee,EmpPlanView employeePlan) throws Exception{
        policyVo.setName(employee.getEmpName()== null?"":String.valueOf(employee.getEmpName()));
        policyVo.setIdNumber(employee.getNewIc());
        policyVo.setCardNo(employee.getCardNo().toString());
        if(employee.getDateOfBirth() != null){
            policyVo.setBirthDate(DateUtils.format(employee.getDateOfBirth(),DateUtils.DATE_TIME_FORMAT_YMD));
            policyVo.setAge(String.valueOf(DateUtils.getAgeByBirth(employee.getDateOfBirth())));
        }else{
            policyVo.setBirthDate("");
            policyVo.setAge("");
        }
        if("M".equals(employee.getGender())){
            policyVo.setGender("男");
        }else if("F".equals(employee.getGender())){
            policyVo.setGender("女");
        }else{
            policyVo.setGender("未知");
        }
        Employee employeeMain = benefitSerivice.getEmployeeInfo(employee.getEmployeeId().trim());
        if(employeeMain != null){
            policyVo.setMainInsure(employeeMain.getEmpName() == null?"":String.valueOf(employeeMain.getEmpName()));
        }else{
            policyVo.setMainInsure("");
        }
        Payor payor = new Payor();
        payor.setPayorCode(employee.getPayorCode());
        payor = payorService.SelectPayorInfoByCondition(payor);
        if(payor != null){
            policyVo.setCorporation(payor.getLongName());
        }
        Card card = benefitSerivice.getCardInfo(employee.getMemberControlNo());
        if(card != null){
            policyVo.setPolicyNo(card.getPolicyNo());
        }else{
            policyVo.setPolicyNo("");
        }
        String startDate = "";
        String endDate="";
        String cancelDate ="";
        if(employeePlan.getStartDate() != null){
            startDate = DateUtils.format(employeePlan.getStartDate(),DateUtils.DATE_TIME_FORMAT_YMD);
        }
        if(employeePlan.getEndDate() != null){
            endDate = DateUtils.format(employeePlan.getEndDate(),DateUtils.DATE_TIME_FORMAT_YMD);
        }
        if(employeePlan.getCancellationDate() != null){
            cancelDate = DateUtils.format(employeePlan.getCancellationDate(),DateUtils.DATE_TIME_FORMAT_YMD);
        }
        policyVo.setEffectTime(startDate);
        policyVo.setEndTime(endDate);
        policyVo.setCancelTime(cancelDate);

        PlanMastInfoWithBLOBs planMastInfoWithBLOBs  =
                planMastService.getPlanMastInfoMapper(employee.getPayorCode(),employeePlan.getCorpCode(),employeePlan.getPlanCode());
        if(planMastInfoWithBLOBs != null && StringUtils.isNotBlank(planMastInfoWithBLOBs.getCashlessServiceArea())){
            policyVo.setDirectArea(planMastInfoWithBLOBs.getCashlessServiceArea());
        }else{
            policyVo.setDirectArea("");
        }
    }
    
    
    /*@RequestMapping("/benefitDetail2")
    public JsonResult<List<BenefitInfoDto>>   getBenefit(){
    	System.out.println("==="+222222);
    	Map<String,Object> maps1=new HashMap<String, Object>();
    	maps1.put("corpCode", "9900000052888");
    	maps1.put("planCode", "ECM-37");
    	maps1.put("coverageCode", "GP");
    	maps1.put("compensationRatio", "80");
    	List<BenefitInfoDto> list= benefitSerivice.getBenefitinfo(maps1);
    	return JsonResult.ok(list);
    }*/
    
    @ApiOperation("打印文件接口")
    @RequestMapping("/print")
    public JsonResult<Map<String,String>> printfile(@RequestBody BenefitPrintDto benefitPrint,HttpServletRequest request,  HttpServletResponse respones){
    	  SymUser user=(SymUser)request.getSession().getAttribute(userKey);//获取登录人的信息
    	  String userId=user.getUsrid();//登录人信息
    	  String printType=benefitPrint.getPrintType();  //要打印的文件类型
    	  String cardNo=benefitPrint.getCardNo(); //保险卡号 
    	  String corpCode=benefitPrint.getCorpCode(); //保险公司编码
    	  Map<String,Object>  map=new HashMap<String,Object>();
    	  map.put("printUrl", printUrl);
    	  map.put("cid", cardNo);
    	  map.put("csts", corpCode);
    	  map.put("usid", userId);
    	  map.put("docCD", printType);
    	  String printUrl=PrinttemplateConfig.getBenfitPrintUrl(map);
    	  Map<String,String> maps=new HashMap<String, String>();
    	  maps.put("printUrl", printUrl);
    	  return JsonResult.ok(maps);
    }

    @Value("${eccs.provider.userid}")
    private String userId;
    @Value("${eccs.proficer.password}")
    private String passwd;
    @Autowired
    private MedicialService medicialService;
    @ApiOperation("身份验证接口")
    @RequestMapping("/checkIdCard")
    public JsonResult<Map<String,String>>  checkIdCard(@RequestBody IdCardDto idCardDto ,HttpServletRequest request,  HttpServletResponse respones) throws Exception{
    	 SymUser user=(SymUser)request.getSession().getAttribute(userKey);//获取登录人的信息
    	 Map<String,String> parmMap=new HashMap<String,String>();
    	 String times=(int) new Date().getTime()+"";
    	 String timeStr=times.substring(1,times.length());
    	//String json=JSONObject.toJSONString(idCardDto);
    	 //String userId="test";
    	 //String passwd="1234567";
    	 idCardDto.setUserId(userId);
    	 idCardDto.setPasswd("iZMY+9qaLDhZYoI/tFHEAA==");
    	 System.out.println("times=="+timeStr);
    	 parmMap.put("Terminalid", medicialService.getTerminalId(user));
    	 parmMap.put("Admission_date", DateUtils.format(new Date(),DateUtils.DATE_TIME_FORMAT_YMDMMDD));
    	 parmMap.put("Coverage_code", idCardDto.getCoverageCode());
    	 parmMap.put("Card_no", idCardDto.getCardNo());
    	 parmMap.put("UserId", idCardDto.getUserId());
    	 parmMap.put("Passwd", idCardDto.getPasswd());
    	 parmMap.put("Terminaldt", DateUtils.format(new Date(),DateUtils.DATE_TIME_FORMAT_YMDMMDD));
    	 parmMap.put("Dep_name", idCardDto.getDepName());
    	 parmMap.put("Systrc", "");
    	 String json=JSONObject.toJSONString(parmMap);
    	 String json1="["+json+"]";
    	 String jsons=EncryptUtil.encrypt(json1, "rZcXb3"+timeStr, timeStr+"123456");
    	 System.out.println("json="+json);
    	 System.out.println("json="+jsons);
    	 System.out.println(timeStr+"."+jsons);
    	 String res= benefitSerivice.checkIdCard(timeStr+"."+jsons.replaceAll("\\+","%2B"),url,"EmployeeVerification");
    	 String result=XmlUtil.getIdCardInfo(res);
    	 System.out.println("result="+result);
    	 String resultData="";
    	 String resultKey="";
    	 if(result!=null){
    		 resultKey=result.substring(0, 10);
    		 resultData=result.substring(11, result.length());
    	 }
    	
    	 String resCode=EncryptUtil.desEncrypt(resultData, "rZcXb3"+resultKey, resultKey+"123456");
    	 Map<String,String> maps=new HashMap<String, String>();
   	     maps.put("result", resCode);
    	 return JsonResult.ok(maps);
    	
    	
    }
    
    public static String desEncrypt() throws Exception {
        try
        {
            String data = "U5Vumuaq6X9Nq1ChJkQHFeWCUnwdy6xo+u2lzMb6Roi1AKzzuXJ6moBC21BMqF3g4HnIuvQZRJ1BGCXQUyK7HFxqzzKpTfpwGpRK+fIMlfJWOAZxSVFJvTgIK6c+YOUfdXtkK/TSDHHOadsx45uSIw==";
            String key = "rZcXb31579258104";
            String iv = "1579258104123456";
            
            byte[] encrypted1 =  new sun.misc.BASE64Decoder().decodeBuffer(data);
            
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);


            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void main(String[] args) throws Exception {
  	  System.out.println(desEncrypt());
  	
	  }
    
    }

